import * as React from 'react';
import { Props, State } from './interface';
import styles from './index.module.less';
import { FILR_TYPE } from '@/components/file-card-list/constants';
import WxImageViewer from 'react-wx-images-viewer';
import classnames from 'classnames';
import { GetFileUrl } from '@/services/index';
import PreviewPdf from '@/components/preview-pdf';
import UploadInput from '@/components/files-uploader-input';
import { Toast } from 'antd-mobile-v2';
import addIcon from '@/assets/images/filePickerImg/add.png';
import deleteIcon from '@/assets/images/filePickerImg/delete.png';

export interface IFileState {
  uid: string;
  name: string;
  url?: string;
  status?: 'error' | 'success' | 'done' | 'uploading' | 'removed';
  size: number;
  type: string;
  netUid?: string;
}

export class FilePicker extends React.Component<Props, State> {
  public static defaultProps = new Props();
  constructor(props) {
    super(props);
    this.state = {
      files: [],
      images: [],
      previewVisible: false,
      previewPdfVisible: false,
      pdfUrl: ''
    };
  }

  componentDidUpdate(prevProps) {
    if (!prevProps.cellProps?.receiveData?.length && this.props.cellProps?.receiveData?.length) {
      this.getFileList();
    }
  }

  getFileList = () => {
    const { cellProps } = this.props;
    const attachmentList = cellProps?.receiveData;
    const { files } = this.state;
    // 如果修改了文件列表，不重新给文件列表赋值
    if (files?.length) { return; }
    const valueData = [];
    for (let i = 0; i < attachmentList.length; i++) {
      valueData.push({
        id: attachmentList[i].id,
        url: attachmentList[i].url,
        name: attachmentList[i].originName || attachmentList[i].name,
        fileSize: attachmentList[i].fileSize || attachmentList[i].size
      });
    }
    this.setState({
      files: valueData
    });
  }

  // 关闭图片预览
  handleCancelPreview = () => {
    this.setState({ previewVisible: false });
  };

  // 点击预览
  handleFileClick = async (file) => {
    const type = this.getFileType(file);
    if (type === FILR_TYPE.IMG) {
      console.log('预览图片');
      const res = await GetFileUrl({ id: file.id, device: 'H5' });
      file.url = res.data;
      this.setState({
        images: [file],
        previewVisible: true
      });
      return;
    } else if (type === FILR_TYPE.PDF) {
      const res = await GetFileUrl({ id: file.id, device: 'H5' });
      this.setState({
        pdfUrl: res.data,
        previewPdfVisible: true
      });
      return;
    } else {
      Toast.info('暂不支持此类型文件预览');
    }
  };


  //  获取文件缩略图
  getFileType = (file) => {
    let fileType = '';
    const type = file.name.match(/.([a-z]+)$/i)?.[1];
    switch (type) {
      case 'png':
      case 'jpg':
      case 'jpeg':
      case 'gif':
      case 'bmp': fileType = FILR_TYPE.IMG; break;
      case 'pdf': fileType = FILR_TYPE.PDF; break;
      case 'pptx':
      case 'ppt': fileType = FILR_TYPE.PPT; break;
      case 'docx':
      case 'doc': fileType = FILR_TYPE.WORD; break;
      case 'xls':
      case 'xlsx': fileType = FILR_TYPE.EXCEL; break;
      case 'zip': fileType = FILR_TYPE.PACKAGE; break;
      default: fileType = FILR_TYPE.OTHER;
    }
    return fileType;
  };

  // 获取展示文件大小
  getFileSizeString = (size) => {
    if (!size) return '';
    if (size > 800 * Math.pow(2, 10)) {
      return `${Math.floor(size / Math.pow(2, 20) * 100) / 100}Mb`;
    }
    return `${Math.floor(size / Math.pow(2, 10) * 100) / 100}Kb`;
  };

  // 上传成功
  onSuccess = (current) => {
    this.setState((prevState) => ({
      files: [current].concat(prevState.files ? prevState.files : [])
    }), () => {
      this.props.onChange && this.props.onChange(this.state.files, current);
    });
  }

  // 点击删除
  onDelete = (e, data) => {
    e.stopPropagation();
    const { onChange } = this.props;
    const newFiles = [...this.state.files];
    const newFilesData = newFiles.filter((item) => item.id !== data.id);
    this.setState({
      files: newFilesData
    }, () => {
      onChange && onChange(this.state.files);
    });
  }

  // 关闭pdf预览
  closePreviewPdf = (data) => {
    this.setState({ previewPdfVisible: data });
  };

  render() {
    const { previewPdfVisible, files, pdfUrl, images, previewVisible, previewIndex } = this.state;
    const renderMode = this.props.cellProps?.renderMode;
    const defaultFileType = this.props.cellProps?.defaultFileType;
    const defaultFileSize = this.props.cellProps?.defaultFileSize;
    const maxFileNumber = this.props.cellProps?.maxFileNumber;
    // console.log('renderMode', renderMode);
    return (
      <div
        className={classnames(styles.fileWrap)}
        style={
          renderMode === 'detail'
            ? { paddingTop: 0 }
            : {}
        }
      >
        <span className={`${styles.itemTitle} ${renderMode === 'detail' ? styles.itemTitleDetail : ''}`}>
          {this.props.name}
        </span>
        {
          renderMode === 'detail' && files?.length === 0 ?
            <div className={styles.defaultValue}>无</div>
            :
            (
              <div className={styles.wrap}>
                {files?.map((item, index) => {
                  return (
                    <div className={classnames(styles.wrapListBox, renderMode === 'detail' ? styles.wrapListBoxDetail : '')} key={index} onClick={() => this.handleFileClick(item)}>
                      {renderMode !== 'detail' && (<div className={styles.close} onClick={(e) => this.onDelete(e, item)}><img src={deleteIcon} alt="" /></div>)}
                      <div className={styles.wrapListItemBox}>
                        <div className={styles.imgBox}>{item.name && <img src={this.getFileType(item)} alt="" />}</div>
                        <div className={styles.textBox}>
                          <div className={styles.name}>{item.name}</div>
                          <div className={styles.size}>{this.getFileSizeString(item.fileSize) || '未知大小'}</div>
                        </div>
                      </div>
                    </div>
                  );
                })}
                {renderMode !== 'detail' && (
                  // 最大文件限制
                  files.length < maxFileNumber && (
                    <div className={styles.inputWrap}>
                      <UploadInput onChange={this.onSuccess} fileSize={defaultFileSize} fileTypeList={defaultFileType} />
                      <div className={styles.addFileBox}>
                        <img src={addIcon} alt="" />
                      </div>
                    </div>
                  )
                )}
              </div>
            )
        }
        {
          previewVisible &&
          <WxImageViewer onClose={() => this.handleCancelPreview()}
            urls={images.map((item) => item.url)}
            index={previewIndex}
          />
        }
        {/* 预览pdf文件 */}
        {previewPdfVisible && <PreviewPdf pdfUrl={pdfUrl} closePreviewPdf={(data) => this.closePreviewPdf(data)} />}
      </div>
    );
  }
}
